package com.example.shardingsheredemo.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class MyDatabaseStandardPreciseAlgorithm implements PreciseShardingAlgorithm<Long> {

    public static final String DATABASE_PREFIX="ds";

    /**
     *  精准分片
     * @param collection 物理数据库集合
     * @param preciseShardingValue 数据分片参数
     * @return
     */

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {

        //逻辑表名
        String logicTableName = preciseShardingValue.getLogicTableName();
        //分片键
        String columnName = preciseShardingValue.getColumnName();
        //分片键值
        Long value = preciseShardingValue.getValue();
        String databaseName = DATABASE_PREFIX + (value % 2);
        if (!collection.contains(databaseName)) {
            throw new UnsupportedOperationException("数据源"+databaseName+"不存在");

        }
        return databaseName;


    }
}
